package com.dawnling.androidutils.ui;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dawnling.androidutils.R;
import com.dawnling.androidutils.adapter.PhotoAdater;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.PermissionManager;

import java.io.File;
import java.util.ArrayList;

public class MyTakePhotoActivity extends TakePhotoActivity {

    private RecyclerView recyclerView;
    private PhotoAdater photoAdater;
    private ArrayList<TImage> photoList = new ArrayList<>();
    private int photoLimitShow = 3;//列表至少3个空白按钮
    private int photoLimit = 5;//限制几张

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        photoAdater = new PhotoAdater(this);
        recyclerView.setAdapter(photoAdater);

        photoList.clear();
        //默认三个空白图片
        for (int i = 0; i < photoLimitShow; i++){
            photoList.add(TImage.of(""));
        }
        photoAdater.setNewData(photoList);

        //点击跳转拍照
        photoAdater.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if ("".equals(photoAdater.getItem(position).getPath())){
                    //跳转拍照
                    File file = new File(Environment.getExternalStorageDirectory(), "/keytop/" + System.currentTimeMillis() + ".jpg");
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    Uri imageUri = Uri.fromFile(file);
                    getTakePhoto().onPickFromCapture(imageUri);
                }else {
                    //浏览大图
                    Toast.makeText(MyTakePhotoActivity.this, "浏览大图", Toast.LENGTH_SHORT).show();
                }
            }
        });

        photoAdater.mListener = new PhotoAdater.Listener() {
            @Override
            public void deleteClick(int position) {
                photoAdater.remove(position);
                usingPhotoSize --;
                //新增空白图 固定3张
                if (photoList.size() <= photoLimitShow){
                    for (int j = 0; j < photoLimitShow - photoList.size(); j++){
                        photoList.add(TImage.of(""));
                    }
                }
                //处理删除操作，小于最大限制一直加一个空白
                if ((usingPhotoSize+1) == photoLimit)
                    photoList.add(usingPhotoSize, TImage.of(""));
                photoAdater.notifyDataSetChanged();
            }
        };
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        showImg(result.getImages());
    }

    //获取有效图片数量
    private int usingPhotoSize = 0;
    private void showImg(ArrayList<TImage> images) {
        if (images.size() > 0) usingPhotoSize ++;
        for (int i = 0; i < photoList.size(); i++){
            if ("".equals(photoList.get(i).getPath())){
                photoAdater.remove(i);
                photoList.add(i, TImage.of(images.get(0).getPath()));
                if (usingPhotoSize >= photoLimitShow && photoList.size() < photoLimit){
                    photoList.add(usingPhotoSize, TImage.of(""));
                }
                return;
            }
        }
    }

    /**
     * 权限请求
     */
    private InvokeParam invokeParam;
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type= PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }
}
